package com.yonyou.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Stack;

public class DB
{
  private static DB DB_INSTANCE = null;
  private static int MAX = 40;
  private static Stack<Connection> CON_POOL = new Stack();

  private static String className = "sun.jdbc.odbc.JdbcOdbcDriver";
  private static String url = "jdbc:odbc:test";

  private static final byte[] lock = new byte[0];

  private DB() throws ClassNotFoundException {
    Class.forName(className);
  }

  public static DB getInstance()
    throws ClassNotFoundException
  {
    if (DB_INSTANCE == null) {
      DB_INSTANCE = new DB();
    }
    return DB_INSTANCE;
  }

  public static Connection getConnection() throws SQLException
  {
    synchronized (lock) {
      if (CON_POOL.isEmpty()) {
        return DriverManager.getConnection(url);
      }
      return (Connection)CON_POOL.pop();
    }
  }

  public static void release(Connection con) throws SQLException
  {
    synchronized (lock) {
      if ((con == null) || (con.isClosed()))
        return;
      if (CON_POOL.size() < MAX + 1)
        CON_POOL.push(con);
      else
        con.close();
    }
  }
}